package com.xiaoge.system.utils;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.AnalyzeRequest;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchPhrasePrefixQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class elasticSearchUtils {
    @Autowired
    public RestHighLevelClient getEsClient;

    //实现搜索
    public List<Map<String,Object>> searchByKeyword(String keyword, int pageNum, int pageSize,String index) throws IOException {
        //条件搜索
        keyword = new String(keyword.getBytes(),"utf-8");
        SearchRequest searchRequest = new SearchRequest(index);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //分页
        sourceBuilder.from(pageNum);
        sourceBuilder.size(pageSize);

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        //高亮
        sourceBuilder.highlighter(highlightBuilder);
        //返回的字段
        sourceBuilder.fetchSource(true);
        String[] includeFields = new String[] {"id","title", "description","category","username","context"};
        String[] excludeFields = new String[] {};
        sourceBuilder.fetchSource(includeFields, excludeFields);

        //精准拼配
       /* TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title",keyword);
        sourceBuilder.query(termQueryBuilder);*/
        //Phrase和Phrase_prefix
        MatchPhrasePrefixQueryBuilder matchPhrasePrefixQueryBuilder = QueryBuilders.matchPhrasePrefixQuery("title", keyword);
        sourceBuilder.query(matchPhrasePrefixQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        searchRequest.source(sourceBuilder);
        SearchResponse response = getEsClient.search(searchRequest, RequestOptions.DEFAULT);

        List<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit documnetFiled: response.getHits().getHits()) {
            Map<String, HighlightField> highlightFields = documnetFiled.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = documnetFiled.getSourceAsMap();
            if (title != null){
                String n_text = "";
                Text[] fragments = title.getFragments();
                for (Text text: fragments){
                    n_text += text;
                }
                sourceAsMap.put("title",n_text);
            }

            //解析高亮int
            list.add(sourceAsMap);
        }
        return list;
    }

    /**
     * 批量往索引里面插入数据
     */
    public Boolean btcInsertIndexContext(List<?> contents,String index) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for (int i = 0; i<contents.size();i++){
            bulkRequest.add(new IndexRequest(index).source(JSON.toJSONString(contents.get(i)),
                    XContentType.JSON));
        }
        BulkResponse bulk = getEsClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }

    /**
     * 创建索引
     */
    public Boolean createIndex(String index) throws IOException {
        CreateIndexRequest request = new CreateIndexRequest(index);
        request.settings(Settings.builder()
                .put("index.number_of_shards", 3)
                .put("index.number_of_replicas", 2)
        );

        CreateIndexResponse createIndexResponse = getEsClient.indices().create(request, RequestOptions.DEFAULT);
        AnalyzeRequest request1 = AnalyzeRequest.withIndexAnalyzer(
                index,
                "ik_max_word",
                "title"
        );
        getEsClient.indices().analyze(request1,RequestOptions.DEFAULT);
        return createIndexResponse.isAcknowledged();
    }
}
